/**
 * Author: Hung Tran
 */
package viettravel.guiandevent.place;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.holoeverywhere.app.ProgressDialog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import viettravel.DAO.Comment;
import viettravel.DAO.PlaceDAO;
import viettravel.DTO.DBCommunication;
import viettravel.DTO.JSONParser;
import viettravel.DTO.ViettravelDTO;
import viettravel.common.Constants;
import viettravel.guiandevent.R;
import viettravel.guiandevent.map.CategoryDialog;
import viettravel.guiandevent.map.GetDirectionDialog;
import viettravel.guiandevent.map.GooglemapV2Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;
import com.google.android.gms.maps.model.LatLng;

public class PlaceDetail extends SherlockActivity {
	private ImageView leftArrowImageView;
	private ImageView rightArrowImageView;
	private Gallery mGallery;
	private int mWidth = 250;
	private int mHeight = 200;
	private int mSelectedImagePosition = 0;
	private List<Drawable> mListImage;
	private GalleryImageAdapter galImageAdapter;
	private ViettravelDTO mViettravelDTO;
	private PlaceDAO mPlaceDAO;
	private int mPlaceId;
	private float mRating;

	private ProgressDialog mProgressDialog;
	@SuppressWarnings("unused")
	private boolean expandableFlag = false;
	// private Context mContext;

	// FB
	private UiLifecycleHelper uiHelper;
	private GraphUser user;
	private final String PENDING_ACTION_BUNDLE_KEY = "viettravel.guiandevent:PendingAction";
	private static final List<String> PERMISSIONS = Arrays
			.asList("publish_actions");
	private PendingAction pendingAction = PendingAction.NONE;

	ArrayList<Comment> arrayListComment = new ArrayList<Comment>();
	ListView listComment;

	// Dialog comment
	// private int RESULT_LOAD_IMAGE = 1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(Constants.THEME);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_place_detail);
		// mContext = this;
		mViettravelDTO = ViettravelDTO.getInstance();
		Bundle extra = getIntent().getExtras();
		mPlaceId = extra.getInt(Constants.EXTRA_PLACE_ID);
		mPlaceDAO = mViettravelDTO.findPlaceById(mPlaceId);
		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayHomeAsUpEnabled(false);
		actionBar.setHomeButtonEnabled(true);
		actionBar.setIcon(R.drawable.ic_back_arrow);
		actionBar.setTitle(mPlaceDAO.getPlaceName());
		actionBar.setBackgroundDrawable(Constants.APP_DRAWABLE);
		// render gallery
		new GetImage().execute(mPlaceId);

		// render assessment
		renderAssessment();
		// Expandable description
		final TextView descriptionText = (TextView) findViewById(R.id.placeDetailDescription);
		final ImageButton expandButton = (ImageButton) findViewById(R.id.placeDetailExpandButton);
		final ImageButton collapseButton = (ImageButton) findViewById(R.id.placeDetailCollapseButton);
		descriptionText.setTypeface(Constants.TYPEFACE_NYALA);
		descriptionText.setText(mPlaceDAO.getPlaceDescription());
		expandButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				expandButton.setVisibility(View.INVISIBLE);
				collapseButton.setVisibility(View.VISIBLE);
				descriptionText.setMaxLines(Integer.MAX_VALUE);
			}
		});
		collapseButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				collapseButton.setVisibility(View.INVISIBLE);
				expandButton.setVisibility(View.VISIBLE);
				descriptionText.setMaxLines(1);
			}
		});
		// List comment
		listComment = (ListView) findViewById(R.id.listComments);
		new GetData().execute(mPlaceId);
		// FB
		uiHelper = new UiLifecycleHelper(this, callback);
		uiHelper.onCreate(savedInstanceState);
		if (savedInstanceState != null) {
			String name = savedInstanceState
					.getString(PENDING_ACTION_BUNDLE_KEY);
			pendingAction = PendingAction.valueOf(name);
		}
	}

	private void renderAssessment() {
		ImageView assessmentStar = (ImageView) findViewById(R.id.assessmentStar);
		RatingBar assessmentRatingbar = (RatingBar) findViewById(R.id.assessmentRatingbar);
		mRating = mPlaceDAO.getRate();
		assessmentRatingbar.setRating(mPlaceDAO.getRate());
		assessmentRatingbar
				.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
					@Override
					public void onRatingChanged(RatingBar ratingBar,
							float rating, boolean fromUser) {
						Log.v(Constants.TAG + "rating", rating + "");
						mRating = rating;
						user = Constants.CURRENT_FACEBOOK_USER;
						if (user == null)
							loginFaceBook(PendingAction.RATING);
						else
							ratePlace(user.getId(), mPlaceId, mRating);
					}
				});
		if (mPlaceDAO.getRate() < 2.5) {
			assessmentStar.setImageDrawable(getResources().getDrawable(
					R.drawable.ic_rate_bad));
		} else if (mPlaceDAO.getRate() < 4) {
			assessmentStar.setImageDrawable(getResources().getDrawable(
					R.drawable.ic_rate_normal));
		} else {
			assessmentStar.setImageDrawable(getResources().getDrawable(
					R.drawable.ic_rate_good));
		}
	}

	private void renderGUI() {
		leftArrowImageView = (ImageView) findViewById(R.id.left_arrow_imageview);
		rightArrowImageView = (ImageView) findViewById(R.id.right_arrow_imageview);
		mGallery = (Gallery) findViewById(R.id.gallery);
		leftArrowImageView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mSelectedImagePosition > 0) {
					--mSelectedImagePosition;
				}
				mGallery.setSelection(mSelectedImagePosition, false);
			}
		});

		rightArrowImageView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mSelectedImagePosition < mListImage.size() - 1) {
					++mSelectedImagePosition;
				}
				mGallery.setSelection(mSelectedImagePosition, false);
			}
		});

		mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				mSelectedImagePosition = pos;
				if (mSelectedImagePosition > 0
						&& mSelectedImagePosition < mListImage.size() - 1) {
					leftArrowImageView.setImageDrawable(getResources()
							.getDrawable(R.drawable.ic_left_arrow));
					rightArrowImageView.setImageDrawable(getResources()
							.getDrawable(R.drawable.ic_right_arrow));
				} else if (mSelectedImagePosition == 0) {
					leftArrowImageView.setImageDrawable(getResources()
							.getDrawable(R.drawable.ic_left_arrow));
				} else if (mSelectedImagePosition == mListImage.size() - 1) {
					rightArrowImageView.setImageDrawable(getResources()
							.getDrawable(R.drawable.ic_right_arrow));
				}
				changeBorderForSelectedImage(mSelectedImagePosition);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});

		galImageAdapter = new GalleryImageAdapter(this, mListImage, mWidth,
				mHeight);
		mGallery.setAdapter(galImageAdapter);

		if (mListImage.size() > 0)
			mGallery.setSelection(mSelectedImagePosition, false);
		if (mListImage.size() == 1)
			rightArrowImageView.setImageDrawable(getResources().getDrawable(
					R.drawable.arrow_right_disabled));

	}

	private void changeBorderForSelectedImage(int selectedItemPos) {
		int count = mGallery.getChildCount();
		for (int i = 0; i < count; i++) {
			ImageView imageView = (ImageView) mGallery.getChildAt(i);
			imageView.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.customview_sliding_image_border));
			imageView.setPadding(3, 3, 3, 3);
		}
		ImageView imageView = (ImageView) mGallery.getSelectedView();
		imageView.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.customview_image_selected_border));
		imageView.setPadding(3, 3, 3, 3);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu _menu) {
		SubMenu subMenuSort = _menu.addSubMenu(this
				.getString(R.string.submenu_placedetail));
		subMenuSort
				.add(Menu.NONE, R.id.placedetail_submenu_id_share_Facebook,
						Menu.NONE,
						this.getString(R.string.placedetail_submenu_sharefb))
				.setIcon(R.drawable.ic_share_facebook);
		subMenuSort.add(Menu.NONE, R.id.placedetail_submenu_id_like_place,
				Menu.NONE,
				this.getString(R.string.placedetail_submenu_likeplace))
				.setIcon(R.drawable.ic_like_place);
		subMenuSort.add(Menu.NONE, R.id.placedetail_submenu_id_addcomment,
				Menu.NONE,
				this.getString(R.string.placedetail_submenu_addcomment))
				.setIcon(R.drawable.ic_comment);
		subMenuSort.add(Menu.NONE, R.id.placedetail_submenu_id_getfriend,
				Menu.NONE,
				this.getString(R.string.placedetail_submenu_getfriend))
				.setIcon(R.drawable.ic_get_friendlists);
		subMenuSort.add(Menu.NONE, R.id.placedetail_submenu_id_getplacearound,
				Menu.NONE,
				this.getString(R.string.placedetail_submenu_getplacearound))
				.setIcon(R.drawable.ic_place_around);
		subMenuSort.add(Menu.NONE, R.id.placedetail_submenu_id_get_direction,
				Menu.NONE,
				this.getString(R.string.placedetail_submenu_getdirections))
				.setIcon(R.drawable.ic_get_direction);

		MenuItem menuItemSort = subMenuSort.getItem();
		menuItemSort.setIcon(R.drawable.ic_list_w);
		menuItemSort.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS
				| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		return super.onCreateOptionsMenu(_menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home: {
			finish();
			return true;
		}
		case R.id.placedetail_submenu_id_share_Facebook: {
			user = Constants.CURRENT_FACEBOOK_USER;
			if (user == null)
				loginFaceBook(PendingAction.POST_STATUS_UPDATE);
			else
				onClickPostStatusUpdate();
			return true;
		}
		case R.id.placedetail_submenu_id_addcomment: {
			user = Constants.CURRENT_FACEBOOK_USER;
			if (user == null)
				loginFaceBook(PendingAction.COMMENT);
			else
				popUpCommentDialog();
			return true;
		}
		case R.id.placedetail_submenu_id_like_place: {
			user = Constants.CURRENT_FACEBOOK_USER;
			if (user == null) {
				loginFaceBook(PendingAction.LIKE_PLACE);
			} else
				likePlace(Constants.CURRENT_FACEBOOK_USER.getId(), mPlaceId);
			return true;
		}
		case R.id.placedetail_submenu_id_get_direction: {
			Intent intent = new Intent(PlaceDetail.this,
					GetDirectionDialog.class);
			intent.putExtra(Constants.MY_LOCATION, "10.8509" + ","
					+ "106.7723");
			Log.v(Constants.TAG,
					mPlaceDAO.getPlaceLat() + ", " + mPlaceDAO.getPlaceLong());
			intent.putExtra(Constants.PLACE_WANT_SEARCH,
					mPlaceDAO.getPlaceLat() + "," + mPlaceDAO.getPlaceLong());
			intent.putExtra(Constants.TAG_PLACES_NAME, mPlaceDAO.getPlaceName());
			startActivity(intent);
			return true;
		}
		case R.id.placedetail_submenu_id_getfriend: {
			user = Constants.CURRENT_FACEBOOK_USER;
			if (user == null)
				loginFaceBook(PendingAction.GET_FRIEND);
			else
				getFriends();
			return true;
		}
		case R.id.placedetail_submenu_id_getplacearound:{
			Intent intent = new Intent(PlaceDetail.this,
					CategoryDialog.class);
			intent.putExtra(Constants.MY_LOCATION,
					mPlaceDAO.getPlaceLat()+ "," + mPlaceDAO.getPlaceLong());
			startActivity(intent);
			return true;
		}
		default:
			return super.onMenuItemSelected(featureId, item);
		}
	}

	public void likePlace(String userId, int placeId) {
		JSONObject type = new JSONObject();
		try {
			type.put(Constants.TAG_RESULT, 2);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONObject json = new JSONObject();
		json = new JSONParser().makeFavoriteJson(placeId, userId);
		new PostData().execute(type, json);
	}

	public void ratePlace(String userId, int placeId, float rating) {
		JSONObject type = new JSONObject();
		try {
			type.put(Constants.TAG_RESULT, 3);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONObject json = new JSONObject();
		json = new JSONParser().makeJsonRate(placeId, userId, (int) rating);
		new PostData().execute(type, json);
	}

	public void loginFaceBook(final PendingAction stateCommand) {
		mProgressDialog = new ProgressDialog(PlaceDetail.this,
				ProgressDialog.THEME_HOLO_LIGHT);
		mProgressDialog.setMessage("Authorize Facebook...");
		mProgressDialog.setCancelable(true);
		mProgressDialog.setIndeterminate(true);
		mProgressDialog.show();

		Session.openActiveSession(this, true, new Session.StatusCallback() {
			@Override
			public void call(Session session, SessionState state,
					Exception exception) {
				if (session.isOpened())
					Request.executeMeRequestAsync(session,
							new Request.GraphUserCallback() {
								@Override
								public void onCompleted(GraphUser _user,
										Response response) {
									mProgressDialog.dismiss();
									if (_user != null) {
										Constants.CURRENT_FACEBOOK_USER = _user;
										user = _user;

										switch (stateCommand) {
										case LIKE_PLACE: {
											postUser(_user.getId(),
													_user.getName());
											likePlace(_user.getId(), mPlaceId);
											break;
										}
										case POST_STATUS_UPDATE: {
											postUser(_user.getId(),
													_user.getName());
											onClickPostStatusUpdate();
											break;
										}
										case COMMENT: {
											postUser(_user.getId(),
													_user.getName());
											popUpCommentDialog();
											break;
										}
										case RATING: {
											postUser(_user.getId(),
													_user.getName());
											ratePlace(user.getId(), mPlaceId,
													mRating);
											break;
										}
										case GET_FRIEND: {
											postUser(_user.getId(),
													_user.getName());
											getFriends();
											break;
										}
										default:
											break;
										}
									}
								}
							});
			}
		});
	}

	public void postUser(String userId, String userName) {
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put(Constants.TAG_RESULT, 1);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		JSONObject json = new JSONParser().makeUserJson(user.getId(),
				user.getName());
		new PostData().execute(jsonObject, json);

	}

	public void popUpCommentDialog() {
		Intent i = new Intent(PlaceDetail.this, PlaceDetailDialogComment.class);
		i.putExtra(Constants.EXTRA_PLACE_ID, mPlaceId);
		startActivity(i);
	}

	/*
	 * Facebook
	 */

	private void getFriends() {
		mProgressDialog = new ProgressDialog(PlaceDetail.this,
				ProgressDialog.THEME_HOLO_LIGHT);
		mProgressDialog.setMessage("Get friend data...");
		mProgressDialog.setCancelable(false);
		mProgressDialog.setIndeterminate(true);
		mProgressDialog.show();

		String fqlQuery = "SELECT uid, name,pic_square, current_location "
				+ "FROM user "
				+ "WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())";

		Bundle params = new Bundle();
		params.putString("q", fqlQuery);
		Session session = Session.getActiveSession();
		/*
		 * session.requestNewReadPermissions(new NewPermissionsRequest(this,
		 * Arrays.asList("friends_location")));
		 */
		Request request = new Request(session, "/fql", params, HttpMethod.GET,
				new Request.Callback() {
					public void onCompleted(Response response) {
						try {
							GraphObject graphObject = response.getGraphObject();
							JSONObject jsonObject = graphObject
									.getInnerJSONObject();
							JSONArray array = jsonObject
									.getJSONArray(Constants.TAG_FB_DATA);
							JSONArray listFriend = new JSONArray();

							Intent intent = new Intent(PlaceDetail.this,
									FriendListsNearLocation.class);
							for (int i = 0; i < array.length(); i++) {

								JSONObject friend = array.getJSONObject(i);
								JSONObject friendLocation = new JSONObject();

								try {
									friendLocation = friend
											.getJSONObject(Constants.TAG_FB_CURRENT_LOCATION);
									if (friendLocation != null
											&& Constants.calculateDistance(
													new LatLng(
															mPlaceDAO
																	.getPlaceLat(),
															mPlaceDAO
																	.getPlaceLong()),
													new LatLng(
															friendLocation
																	.getDouble(Constants.TAG_FB_LATITUE),
															friendLocation
																	.getDouble(Constants.TAG_FB_LONGTITUTE))) < Constants.DISTANCE * 1000) {
										listFriend.put(friend);
									}
								} catch (JSONException e) {
									Log.e(Constants.TAG,
											"Loi parse current_location");
								}

							}
							intent.putExtra(
									Constants.EXTRA_PLACE_LAT,
									mPlaceDAO.getPlaceLat() + ","
											+ mPlaceDAO.getPlaceLong());
							intent.putExtra(Constants.EXTRA_PLACE_NAME,
									mPlaceDAO.getPlaceName());
							intent.putExtra(Constants.EXTRA_GETFRIEND,
									listFriend.toString());
							mProgressDialog.dismiss();
							startActivity(intent);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
		Request.executeBatchAsync(request);
	}

	private enum PendingAction {
		NONE, LIKE_PLACE, POST_STATUS_UPDATE, COMMENT, RATING, GET_FRIEND
	}

	private void onClickPostStatusUpdate() {
		performPublish(PendingAction.POST_STATUS_UPDATE);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);
	}

	private void performPublish(PendingAction action) {
		Session session = Session.getActiveSession();
		if (session != null) {
			pendingAction = action;
			if (hasPublishPermission())
				handlePendingAction();
			else
				session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
						this, PERMISSIONS));
		}
	}

	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	private void onSessionStateChange(Session session, SessionState state,
			Exception exception) {
		if (pendingAction != PendingAction.NONE
				&& (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException)) {
			new org.holoeverywhere.app.AlertDialog.Builder(PlaceDetail.this)
					.setTitle(R.string.fb_cancel)
					.setMessage(R.string.fb_permission_not_granted)
					.setPositiveButton(R.string.fb_Ok, null).show();
			pendingAction = PendingAction.NONE;
		} else if (state == SessionState.OPENED_TOKEN_UPDATED)
			handlePendingAction();
	}

	@SuppressWarnings("incomplete-switch")
	private void handlePendingAction() {
		PendingAction previouslyPendingAction = pendingAction;
		pendingAction = PendingAction.NONE;
		switch (previouslyPendingAction) {
		case POST_STATUS_UPDATE:
			postStatusUpdate();
			break;
		}
	}

	private void postStatusUpdate() {
		if (user != null && hasPublishPermission()) {
			final String message = "Viettravel testing......";
			Request request = Request.newStatusUpdateRequest(
					Session.getActiveSession(), message,
					new Request.Callback() {
						@Override
						public void onCompleted(Response response) {
							showPublishResult(message,
									response.getGraphObject(),
									response.getError());
						}
					});
			request.executeAsync();
		} else {
			pendingAction = PendingAction.POST_STATUS_UPDATE;
		}
	}

	private boolean hasPublishPermission() {
		Session session = Session.getActiveSession();
		return session != null
				&& session.getPermissions().contains("publish_actions")
				&& session.getPermissions().contains("friends_location");
	}

	private void showPublishResult(String message, GraphObject result,
			FacebookRequestError error) {
		String title = null;
		String alertMessage = null;
		if (error == null) {
			title = getString(R.string.fb_success_title);
			String id = result.cast(GraphObjectWithId.class).getId();
			alertMessage = getString(R.string.fb_success_message, message, id);
		} else {
			title = getString(R.string.fb_error);
			alertMessage = error.getErrorMessage();
		}
		new org.holoeverywhere.app.AlertDialog.Builder(this).setTitle(title)
				.setMessage(alertMessage)
				.setPositiveButton(R.string.fb_Ok, null).show();
	}

	private interface GraphObjectWithId extends GraphObject {
		String getId();
	}

	public class PostData extends AsyncTask<JSONObject, Void, Boolean> {

		private ProgressDialog mProgressDialog;

		@Override
		protected void onPreExecute() {
			mProgressDialog = new ProgressDialog(PlaceDetail.this,
					ProgressDialog.THEME_HOLO_LIGHT);
			mProgressDialog.setMessage("Post data...");
			mProgressDialog.setCancelable(false);
			mProgressDialog.setIndeterminate(true);
			mProgressDialog.show();
		};

		@Override
		protected void onPostExecute(Boolean result) {
			if (mProgressDialog.isShowing()) {
				mProgressDialog.dismiss();
			}
		}

		@Override
		protected Boolean doInBackground(JSONObject... params) {
			int type = 0;
			try {
				type = params[0].getInt(Constants.TAG_RESULT);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (type == 1)
				return DBCommunication.postData(Constants.ROOT,
						Constants.SUFFIX_POST_USER, params[1]);
			else if (type == 2)
				return DBCommunication.postData(Constants.ROOT,
						Constants.SUFFIX_POST_FAVORITEPLACE, params[1]);
			else if (type == 3)
				return DBCommunication.postData(Constants.ROOT,
						Constants.SUFFIX_POST_RATE, params[1]);
			else
				return false;
		}
	}

	public class GetData extends AsyncTask<Integer, Void, ArrayList<Comment>> {
		private ProgressDialog mProgressDialog;

		@Override
		protected void onPreExecute() {
			mProgressDialog = new ProgressDialog(PlaceDetail.this,
					ProgressDialog.THEME_HOLO_LIGHT);
			mProgressDialog.setMessage("Get comments...");
			mProgressDialog.setCancelable(false);
			mProgressDialog.setIndeterminate(true);
			mProgressDialog.show();
		};

		@Override
		protected void onPostExecute(ArrayList<Comment> result) {
			if (mProgressDialog.isShowing()) {
				mProgressDialog.dismiss();
				arrayListComment = result;
				ListCommentAdapter listCommentAdapter = new ListCommentAdapter(
						arrayListComment, getBaseContext());
				listComment.setAdapter(listCommentAdapter);
			}
		}

		@Override
		protected ArrayList<Comment> doInBackground(Integer... params) {
			return DBCommunication.parserComments(Constants.ROOT,
					Constants.SUFFIX_GET_COMMENTS, params[0]);

		}
	}

	public class GetImage extends AsyncTask<Integer, Void, ArrayList<Drawable>> {

		private ProgressDialog mProgressDialog;

		@Override
		protected void onPreExecute() {
			mProgressDialog = new ProgressDialog(PlaceDetail.this,
					ProgressDialog.THEME_HOLO_LIGHT);
			mProgressDialog.setMessage("Get images...");
			mProgressDialog.setCancelable(false);
			mProgressDialog.setIndeterminate(true);
			mProgressDialog.show();
		};

		@Override
		protected void onPostExecute(ArrayList<Drawable> result) {
			if (mProgressDialog.isShowing()) {
				mProgressDialog.dismiss();
				mListImage = new ArrayList<Drawable>();
				mListImage = result;
				renderGUI();
			}
		}

		@Override
		protected ArrayList<Drawable> doInBackground(Integer... params) {
			return DBCommunication.parserImages(Constants.ROOT,
					Constants.SUFFIX_GET_IMAGES, params[0]);
		}
	}
}
